package com.techzhi.tidb.config;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.util.StringUtils;
import java.util.HashMap;
import java.util.Map;

/**
 * TiDB配置管理器
 * 集中管理TiDB连接配置，支持多环境、加密存储
 *
 * @author shouzhi
 * @date 2025-09-01
 */
@Data
@Slf4j
@ConfigurationProperties(prefix = "tidb")
public class TiDBConfigManager {

    /**
     * TiDB连接配置
     */
    private TiDBConfig config = new TiDBConfig();

    /**
     * 是否启用TiDB
     */
    private boolean enabled = false;

    /**
     * 连接池配置
     */
    private PoolConfig pool = new PoolConfig();

    /**
     * 安全配置
     */
    private SecurityConfig security = new SecurityConfig();

    @Data
    public static class TiDBConfig {
        private String host = "192.168.50.9";
        private Integer port = 4000;
        private String database = "jdf";
        private String username = "root";
        private String password = "Root_123";
        private String charset = "utf8mb4";
        private String timezone = "Asia/Shanghai";
        private Map<String, String> properties = new HashMap<>();

        public TiDBConfig() {
            // 设置TiDB默认属性
            properties.put("useUnicode", "true");
            properties.put("useSSL", "false");
            properties.put("allowPublicKeyRetrieval", "true");
            properties.put("rewriteBatchedStatements", "true");
            properties.put("allowMultiQueries", "true");
            properties.put("useCompression", "true");
        }
    }

    @Data
    public static class PoolConfig {
        private int maximumPoolSize = 20;
        private int minimumIdle = 5;
        private long connectionTimeout = 30000;
        private long idleTimeout = 600000;
        private long maxLifetime = 1800000;
        private String poolName = "TiDB-HikariCP";
        private long leakDetectionThreshold = 60000;
        private boolean autoCommit = true;
    }

    @Data
    public static class SecurityConfig {
        private boolean encryptPassword = true;
        private boolean enableSsl = false;
        private long validationTimeout = 5000;
        private String connectionTestQuery = "SELECT 1";
    }

    /**
     * 获取加密后的密码
     */
    public String getEncryptedPassword() {
        if (!security.isEncryptPassword()) {
            return config.getPassword();
        }
        //return NvxJasyptUtils.encode(config.getPassword());
        return config.getPassword();
    }

    /**
     * 获取解密后的密码
     */
    public String getDecryptedPassword() {
        if (!security.isEncryptPassword()) {
            return config.getPassword();
        }
        try {
            //return NvxJasyptUtils.decode(config.getPassword());
            return config.getPassword();
        } catch (Exception e) {
            log.warn("密码解密失败，使用原密码: {}", e.getMessage());
            return config.getPassword();
        }
    }

    /**
     * 构建JDBC URL
     */
    public String buildJdbcUrl() {
        StringBuilder url = new StringBuilder();
        url.append("jdbc:mysql://")
           .append(config.getHost())
           .append(":")
           .append(config.getPort())
           .append("/")
           .append(config.getDatabase());

        // 添加基础参数
        url.append("?characterEncoding=").append(config.getCharset())
           .append("&serverTimezone=").append(config.getTimezone());

        // 添加自定义属性
        config.getProperties().forEach((key, value) ->
            url.append("&").append(key).append("=").append(value));

        return url.toString();
    }

    /**
     * 验证配置有效性
     */
    public boolean validateConfig() {
        if (!StringUtils.hasText(config.getHost())) {
            log.error("TiDB主机地址不能为空");
            return false;
        }

        if (config.getPort() == null || config.getPort() <= 0 || config.getPort() > 65535) {
            log.error("TiDB端口号无效: {}", config.getPort());
            return false;
        }

        if (!StringUtils.hasText(config.getDatabase())) {
            log.error("TiDB数据库名不能为空");
            return false;
        }

        if (!StringUtils.hasText(config.getUsername())) {
            log.error("TiDB用户名不能为空");
            return false;
        }

        if (!StringUtils.hasText(config.getPassword())) {
            log.error("TiDB密码不能为空");
            return false;
        }

        return true;
    }

    /**
     * 获取掩码后的连接信息（用于日志输出）
     */
    public String getMaskedConnectionInfo() {
        return String.format("TiDB[%s:%d/%s@%s]",
            config.getHost(),
            config.getPort(),
            config.getDatabase(),
            config.getUsername());
    }

    /**
     * 获取掩码后的JDBC URL（用于日志输出）
     */
    public String getMaskedJdbcUrl() {
        String url = buildJdbcUrl();
        return url.replaceAll("password=[^&]*", "password=***");
    }
}
